<template>
  <div class="booking-create-container">
    <el-card class="booking-card">
      <template #header>
        <div class="card-header">
          <span>创建预约</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" v-if="!unavailable">
        <el-form-item label="选择场地" prop="venueId">
          <el-select v-model="form.venueId" placeholder="请选择场地" filterable style="width:100%">
            <el-option v-for="venue in venues" :key="venue.id" :label="venue.name" :value="venue.id" :disabled="venue.status !== 1" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择教练" prop="coachId">
          <el-select v-model="form.coachId" placeholder="请选择教练" filterable style="width:100%">
            <el-option v-for="coach in coaches" :key="coach.id" :label="coach.name" :value="coach.id" :disabled="coach.status !== 1" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程" filterable style="width:100%" @change="handleCourseChange">
            <el-option v-for="course in courses" :key="course.id" :label="course.title" :value="course.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程金额">
          <el-input v-model="form.price" readonly placeholder="请选择课程" />
        </el-form-item>
        <el-form-item label="预约时间" prop="bookingTime">
          <el-date-picker v-model="form.bookingTime" type="datetime" placeholder="选择预约时间" style="width:100%" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitBooking" :loading="submitting">提交预约</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
      <div v-else class="unavailable-tip">
        <el-result icon="error" title="不可预约" sub-title="当前选择的场地或教练不可用，请返回重新选择。">
          <template #extra>
            <el-button type="primary" @click="goBack">返回</el-button>
          </template>
        </el-result>
      </div>
    </el-card>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { venueApi, coachApi, bookingApi } from '@/api'
import { courseApi } from '@/api'
const router = useRouter()
const route = useRoute()
const formRef = ref()
const venues = ref([])
const coaches = ref([])
const courses = ref([])
const form = ref({ venueId: '', coachId: '', courseId: '', price: '', bookingTime: '' })
const rules = {
  venueId: [{ required: true, message: '请选择场地', trigger: 'change' }],
  coachId: [{ required: true, message: '请选择教练', trigger: 'change' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  bookingTime: [{ required: true, message: '请选择预约时间', trigger: 'change' }]
}
const submitting = ref(false)
const unavailable = ref(false)
const goBack = () => { router.back() }

const fetchVenues = async () => {
  const res = await venueApi.getVenueList()
  venues.value = res.data.venues || []
}
const fetchCoaches = async () => {
  const res = await coachApi.getCoachList()
  coaches.value = res.data.coaches || []
}
const fetchCourses = async () => {
  const res = await courseApi.getCourseList ? await courseApi.getCourseList() : await courseApi.getCourseList({})
  courses.value = res.data.activities || []
}
const handleCourseChange = (courseId) => {
  const course = courses.value.find(c => c.id === courseId)
  form.value.price = course ? course.price : ''
}
onMounted(async () => {
  await Promise.all([fetchVenues(), fetchCoaches(), fetchCourses()])
  // 处理 query 参数
  const { venueId, coachId, courseId } = route.query
  if (venueId) form.value.venueId = Number(venueId)
  if (coachId) form.value.coachId = Number(coachId)
  if (courseId) {
    form.value.courseId = Number(courseId)
    handleCourseChange(Number(courseId))
  }
  // 判断是否不可预约
  const selectedVenue = venues.value.find(v => v.id === form.value.venueId)
  const selectedCoach = coaches.value.find(c => c.id === form.value.coachId)
  if ((selectedVenue && selectedVenue.status !== 1) || (selectedCoach && selectedCoach.status !== 1)) {
    unavailable.value = true
  }
})

const submitBooking = async () => {
  await formRef.value.validate()
  submitting.value = true
  try {
    await bookingApi.createBooking({
      userId: localStorage.getItem('userId'),
      activityId: form.value.courseId,
      venueId: form.value.venueId,
      coachId: form.value.coachId,
      price: form.value.price,
      bookingTime: form.value.bookingTime
    })
    ElMessage.success('预约成功')
    router.push('/user/bookings')
  } catch (e) {
    ElMessage.error('预约失败')
  } finally {
    submitting.value = false
  }
}
</script>
<style scoped>
.booking-create-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 0;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
.booking-card {
  width: 480px;
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(102,126,234,0.10);
  background: rgba(255,255,255,0.98);
}
.card-header {
  font-size: 1.3rem;
  font-weight: 700;
  color: #3a3a6a;
  text-align: center;
}
.unavailable-tip {
  padding: 40px 0;
}
</style> 